define(['./PageView', "jquery", '../libs/canlendar', '../libs/AjaxUtil', '../libs/CommonTools', '../libs/GetAction', '../libs/util'], function (PageView, $, Canlendar, AjaxUtil, CommonTools, GetAction, util) {

    return PageView.extend({
        events:{
            'click .left': 'sureBack',
            'click .select-goal-type': 'goToSelectType',
            'click .save-btn': 'saveGoal',
            'click .save-next-btn': 'saveGoResult',
            'input #goal-text': 'btnStatusChange',
        },
        goalType: 1,   //类别,默认是1 , 1代表个人OKRs , 2代表部门OKRs

        initialize: function () {
            require('../../less/GoalAddNEdit.less');
            this.beginGoalValue = "";
            this.beginCycleValue = "";
            this.beginTypeValue = "";
        },
        render: function () {
            PageView.prototype.render.apply(this, arguments);
            var tpl = require('../templates/GoalAddNEdit.html');
            this.$main = $('<div class="main"></div>');
            this.$wrap = $('<div class="content"></div>');
            this.$wrap.append(tpl);
            this.$main.append(this.$wrap);
            this.$el.append(this.$main);
            return this;
        },
        onRender: function(){
            this.initPage();
            var href = window.location.href;
            if(href.indexOf("target_id") > -1){
                var start = href.indexOf("target_id");
                var test = href.substr(start+10,href.length);
                this.$el.find('.title').text("编辑目标");
                this.$el.find('.select-goal-type').hide();
                this.$el.find('.save-next-btn').hide();
                var data = JSON.parse(sessionStorage.getItem("goalData"));
                this.$el.find('#goal-text').val(data.description);
                this.$el.find('.save-btn').removeClass("btn-disabled");
            }
            else{
                this.$el.find('.title').text("新增目标");
                this.$el.find('.select-goal-type').show();
                this.$el.find('.save-next-btn').show();
                this.$el.find('.save-btn').addClass("btn-disabled");
                this.$el.find('.save-next-btn').addClass("btn-disabled");
                this.$el.find('#goal-text').val("");
            }

        },
        onResume: function(){
            this.initPage();
            if(window.app.valueStr){
                this.$el.find('.select-goal-type .right-part-label').text(window.app.valueStr);
                this.goalType = window.app.type;
            }
            else{
                this.$el.find('.select-goal-type .right-part-label').text("个人OKRs");
            }
        },
        setBegin: function(){
            //设置存储初始值
            this.beginGoalValue = this.$el.find('#goal-text').val();
            this.beginCycleValue = this.$el.find("#goal-cycle-view").val();
            this.beginTypeValue = this.$el.find('.select-goal-type .right-part-label').text();
        },
        isChange: function(){
            var href = window.location.href;
            var goalVal = this.$el.find('#goal-text').val();
            var cycleVal = this.$el.find("#goal-cycle-view").val();
            var typeVal = this.$el.find('.select-goal-type .right-part-label').text();
            console.log(goalVal+","+cycleVal+","+typeVal);
            if(href.indexOf("target_id") > -1){
                if(goalVal==this.beginGoalValue){
                    return false;
                }
                else{
                    return true;
                }
            }
            else{
                if(goalVal==this.beginGoalValue && typeVal=="个人OKRs" && cycleVal==this.beginCycleValue){
                    return false;
                }
                else{
                    return true;
                }
            }
        },
        selectDefault: function(){
            var href = window.location.href;
            if(href.indexOf("target_id") > -1){
                //编辑目标时选中原来的周期
                var data = JSON.parse(sessionStorage.getItem("goalData"));
                var cycle = data.cycle;
                this.$el.find("#goal-cycle-view").val(cycle);
                this.$el.find("#goal-cycle-view").attr("disabled","disabled");
            }
            else{
                //新增目标时选中当前周期
                this.$el.find("#goal-cycle-view").removeAttr("disabled");
            }
        },
        initPage: function(){
            //该方法用于区分该页面是编辑还是新增
            var _this = this;
            var href = window.location.href;
            this.selectDefault();
            if(href.indexOf("target_id") > -1){
                this.$el.find('.title').text("编辑目标");
                this.$el.find('.select-goal-type').hide();
                this.$el.find('.save-next-btn').hide();
                var data = JSON.parse(sessionStorage.getItem("goalData"));
                this.$el.find('#goal-text').val(data.description);
                this.$el.find('.save-btn').removeClass("btn-disabled");
                this.setBegin();
            }
            else{
                this.$el.find('.title').text("新增目标");
                this.$el.find('.select-goal-type').show();
                this.$el.find('.save-next-btn').show();
                this.$el.find('#goal-text').val("");
                this.$el.find('.save-btn').addClass("btn-disabled");
                this.$el.find('.save-next-btn').addClass("btn-disabled");
            }
            //请求周期接口
            AjaxUtil.ajaxPost({
                path: '/client/cycle/selector',
                params: {now:0},
                success: function (data) {
                    if(data.length != 0){
                        //把获得的周期渲染到select标签中去
                        _this.$el.find('#goal-cycle-view').html("");   //先清空option
                        for(var i=0 ; i<data.length ; i++){
                            var option = '<option value='+ data[i].cycle +' data-id='+ data[i].cycleId +'>'+ data[i].cycle +'</option>';
                            _this.$el.find('#goal-cycle-view').append(option);
                        }
                        _this.selectDefault();
                        _this.setBegin();
                    }
                    else{
                        CommonTools.Toast("获取周期失败!");
                    }

                },
                error: function () {
                    CommonTools.Toast("请检查网络!");
                }
            });

        },
        btnStatusChange: function(){

            var inputVal = this.$el.find('#goal-text').val();
            if(inputVal.length>0){
                this.$el.find('.btn').removeClass('btn-disabled');
            }
            else{
                this.$el.find('.btn').addClass('btn-disabled');
            }
        },
        resetPage: function(){
            //重置页面
            var href = window.location.href;
            if(href.indexOf("target_id") > -1){

            }
            else{
                this.$el.find('#goal-text').val("");
                this.$el.find("#goal-cycle-view option:first").prop("selected", 'selected');
                this.$el.find('.btn-group-block .btn').addClass("btn-disabled");
                window.app.valueStr = null;
                window.app.type = 1;
                this.$el.find('.select-goal-type .right-part-label').text("个人OKRs");
            }
        },
        addGoal: function(e){
            //添加新目标请求
            var _this =this;
            //按钮状态,0为可点击,1为不可点击
            var btnStatus = $(e.target).hasClass('btn-disabled') ? 1 : 0 ;
            var IsBtnNext = $(e.target).hasClass('save-next-btn');
            if(btnStatus==1){
                return;
            }
            if(this.checkGoalContent()){
                var description = this.$el.find('#goal-text').val();
                //判断设备,2为安卓,3为IOS
                var u = navigator.userAgent;
                var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
                var platform = 2;
                if(isiOS){
                    platform = 3;
                }
                var cycle = this.$el.find("#goal-cycle-view option:selected").val();
                var cycleId = this.$el.find("#goal-cycle-view option:selected").attr("data-id");
                var ownerType = this.goalType;  //默认是1 , 1代表个人OKRs , 2代表部门OKRs
                AjaxUtil.ajaxPost({
                    path: '/client/objective/app/add',
                    params: {
                        ownerType: ownerType,
                        description: description,
                        cycle: cycle,
                        source: platform,
                        cycleId: cycleId
                    },
                    success: function (data) {
                        if(data.length != 0){
                            CommonTools.Toast("新增目标成功!");
                            //此处把选择目标类型的变量置为空
                            window.app.valueStr = null;
                            window.app.type = 1;
                            //不同按钮不同跳转
                            if(IsBtnNext){
                                //保存并新增下关键结果
                                CommonTools.Toast("新增目标成功!",1000,function(){
                                    Backbone.history.navigate('#KeyResultAdd?target_id='+data.id,{
                                        trigger:true,
                                        replace:true
                                    });
                                    //重置页面信息
                                    _this.resetPage();
                                });
                            }
                            else{
                                //保存成功返回
                                CommonTools.Toast("新增目标成功!",1000,function(){_this.back();});
                            }
                        }
                        else{
                            CommonTools.Toast("新增目标失败!");
                        }

                    },
                    error: function () {
                        CommonTools.Toast("请检查网络!");
                    }
                });
            }
        },
        saveGoal: function(e){
            var href = window.location.href;
            if(href.indexOf("target_id") > -1){
                //判断是否为编辑页面,调用不同接口
                this.saveEdit();
            }
            else{
                this.addGoal(e);
            }
        },
        saveEdit: function(){
            //保存编辑结果
            var _this = this;
            var href = window.location.href;
            var start = href.indexOf("target_id");
            var cycle = this.$el.find("#goal-cycle-view option:selected").val();
            var cycleId = this.$el.find("#goal-cycle-view option:selected").attr("data-id");
            var id = href.substr(start+10,href.length);
            var description = this.$el.find('#goal-text').val();
            AjaxUtil.ajaxPost({
                path: '/client/objective/app/update',
                params: {
                    description: description,
                    id: id
                },
                success: function (data) {
                    CommonTools.Toast("保存成功!",1000,function(){_this.back();});
                },
                error: function () {
                    CommonTools.Toast("请检查网络!");
                }
            });
        },
        saveGoResult: function(e){
            this.addGoal(e);
        },
        checkGoalContent: function(){
            var content = this.$el.find('#goal-text').val();
            if(content.length == 0){
                CommonTools.Toast("请填写目标!");
                return false;
            }
            else if(content.length > 50){
                CommonTools.Toast("目标字数不能超过50字!");
                return false;
            }
            else{
                return true;
            }
        },
        sureBack: function(){
            var _this = this;
            this.isChange();
            if(this.isChange()){
                CommonTools.confirm("您输入的内容还未保存,确定要返回吗?",function(){_this.back()},function(){});
            }
            else{
                this.back();
            }

        },
        back: function () {
            Backbone.history.history.back();
            this.resetPage();
        },
        goToSelectType: function(){
            Backbone.history.navigate('#SelectGoalType',{
                trigger:true
            });
        },
    });
});